import {FormBase, ControlType} from './form-base';
import {format} from 'date-fns';

export class FormText extends FormBase<string> {
    controlType: ControlType = 'text';
    _value: any;
    isImg = false;

    get value(): string {
        return this._value;

    }

    set value(data) {
        if (data) {
            if (this.isImg) {
                try {
                    this._value = JSON.parse(data);
                } catch (e) {
                    this._value = [];
                }
            } else {
                if (typeof data === 'number') {
                    if ((<number>data).toString().length === 13) {
                        this._value = format(data, 'YYYY-MM-DD');
                    } else {
                        this._value = data;
                    }
                } else if (typeof data === 'string' && !data.startsWith('[')) {
                    this._value = data;
                } else {
                    try {
                        this._value = (<any[]>JSON.parse(data)).toString();
                    } catch (e) {
                        this._value = data;
                    }
                }
            }
        } else {
            this._value = '';
        }
    }

    constructor(options: {} = {}) {
        super(options);
        this.isImg = options['isImg'] || false; // 必须在前
        this.value = options['value'];
    }
}
